package com.ruoyi;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;

import java.util.List;
import java.util.Properties;

/**
 * 客户端订阅服务端实例列表
 * 通过客户端对象去订阅一个服务，当这个服务发生变更的时候就会回调EventListener监听器的onEvent方法
 */
public class NacosSubscribeExample {
    public static void main(String[] args) throws Exception {
        // 配置Nacos Server地址
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");

        // 创建NamingService实例
        NamingService namingService = NacosFactory.createNamingService(properties);

        // 订阅服务
        String serviceName = "ruoyi-system";
        namingService.subscribe(serviceName, event -> {
            // 处理服务变更事件
            if (event instanceof NamingEvent) {
                NamingEvent namingEvent = (NamingEvent) event;
                List<Instance> instances = namingEvent.getInstances();

                System.out.println("服务实例变更通知：");
                System.out.println("服务名：" + namingEvent.getServiceName());
                System.out.println("当前可用实例：");
                for (Instance instance : instances) {
                    System.out.println("- " + instance.getIp() + ":" + instance.getPort()
                            + " (健康状态: " + instance.isHealthy() + ")");
                }

                // 这里可以添加业务逻辑，如更新负载均衡器
                updateLoadBalancer(instances);
            }
        });

        System.out.println("已订阅服务：" + serviceName);

        // 保持主线程运行，避免程序退出
        Thread.currentThread().join();
    }

    private static void updateLoadBalancer(List<Instance> instances) {
        // 示例：更新负载均衡器中的服务列表
        System.out.println("更新负载均衡器...");
        // 实际项目中可能会调用负载均衡器的API进行更新
    }
}